const { getMessagePagingDao, createMessageDao, deleteMessageDao } = require("../dao/messageDao")
const { formatResponseBody } = require("../utils/tools");
const { Op } = require("sequelize");
const { getRandomAvatarPath } = require("../utils/tools");
const { validate } = require("validate.js");
const { ValidationError } = require("../utils/errors");

const rule = {
    nickname: {
        type: "string",
        presence: {
            allowEmpty: false
        }
    },
    content: {
        type: "string",
        presence: {
            allowEmpty: false
        }
    }
}

/**
 * 分页获取留言
 * @param {object} options 
 */
exports.getMessagePagingService = async ({ page = 1, limit = 10, keyword }) => {
    // 将需要的参数准备好
    const where = {};
    if (keyword) {
        where.content = {
            [Op.like]: `%${keyword}%`
        }
    }

    // 组装响应格式
    const result = await getMessagePagingDao((page - 1) * limit, +limit, where);
    const data = {
        total: result.count,
        rows: result.rows.map(item => item.dataValues)
    }
    return formatResponseBody({ data });
}

/**
 * 新增留言
 * @param {object} msg 
 * @returns 
 */
exports.createMessageService = async (msg) => {

    const result = validate(msg, rule);
    if(result) {
        throw new ValidationError("数据验证失败");
    }

    // 初始化一些数据
    msg.createDate = Date.now();
    // 随机选择头像
    msg.avatar = getRandomAvatarPath()

    const data = await createMessageDao(msg)
    return formatResponseBody({ data });
}

/**
 * 删除留言
 * @param {number} id 
 * @returns 
 */
exports.deleteMessageService = async (id) => {
    const result = await deleteMessageDao(id);
    return formatResponseBody({ data: !!result });
}